import sys
import os
import hashlib

# 添加项目根目录到系统路径admin
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from database import Database

class UserCreator:
    def __init__(self):
        self.db = Database()
    
    def create_user(self, username, password, role, name=None, contact=None):
        """
        创建新用户
        
        参数:
            username (str): 用户名
            password (str): 密码
            role (str): 角色（admin/teacher/student）
            name (str): 姓名
            contact (str): 联系方式
        
        返回:
            bool: 创建成功返回True，否则返回False
        """
        try:
            # 验证输入
            if not username or not password or not role:
                print("错误：用户名、密码和角色必须填写")
                return False
            
            # 验证角色是否有效
            valid_roles = ['admin', 'teacher', 'student']
            if role not in valid_roles:
                print(f"错误：角色必须是 {', '.join(valid_roles)} 之一")
                return False
            
            # 连接数据库
            self.db.connect()
            
            # 检查用户名是否已存在
            self.db.cursor.execute(
                "SELECT id FROM user WHERE username = ?",
                (username,)
            )
            if self.db.cursor.fetchone():
                print(f"错误：用户名 {username} 已存在")
                self.db.close()
                return False
            
            # 对密码进行哈希处理
            hashed_password = hashlib.sha256(password.encode()).hexdigest()
            
            # 插入新用户
            self.db.cursor.execute(
                "INSERT INTO user (username, password, role, name, contact) VALUES (?, ?, ?, ?, ?)",
                (username, hashed_password, role, name, contact)
            )
            self.db.conn.commit()
            print(f"成功：用户 {username} 创建成功，角色为 {role}")
            return True
        except Exception as e:
            print(f"错误：创建用户时发生错误 - {str(e)}")
            return False
        finally:
            self.db.close()
    
    def batch_create_users(self, users_data):
        """
        批量创建用户
        
        参数:
            users_data (list): 用户信息列表，每个元素是包含用户信息的元组
                              (username, password, role, name, contact)
        
        返回:
            tuple: (成功创建数量, 总数量)
        """
        success_count = 0
        total_count = len(users_data)
        
        try:
            self.db.connect()
            
            for user_data in users_data:
                username, password, role, name, contact = user_data
                
                # 验证输入
                if not username or not password or not role:
                    print(f"错误：用户 {username} 的信息不完整，跳过")
                    continue
                
                # 验证角色是否有效
                valid_roles = ['admin', 'teacher', 'student']
                if role not in valid_roles:
                    print(f"错误：用户 {username} 的角色必须是 {', '.join(valid_roles)} 之一，跳过")
                    continue
                
                # 检查用户名是否已存在
                self.db.cursor.execute(
                    "SELECT id FROM user WHERE username = ?",
                    (username,)
                )
                if self.db.cursor.fetchone():
                    print(f"错误：用户名 {username} 已存在，跳过")
                    continue
                
                # 对密码进行哈希处理
                hashed_password = hashlib.sha256(password.encode()).hexdigest()
                
                # 插入新用户
                try:
                    self.db.cursor.execute(
                        "INSERT INTO user (username, password, role, name, contact) VALUES (?, ?, ?, ?, ?)",
                        (username, hashed_password, role, name, contact)
                    )
                    self.db.conn.commit()
                    success_count += 1
                    print(f"成功：用户 {username} 创建成功，角色为 {role}")
                except Exception as e:
                    print(f"错误：创建用户 {username} 时发生错误 - {str(e)}")
                    self.db.conn.rollback()
            
            return success_count, total_count
        except Exception as e:
            print(f"错误：批量创建用户时发生错误 - {str(e)}")
            return success_count, total_count
        finally:
            self.db.close()
    
    def batch_create_student_users_by_class(self, class_name):
        """
        根据班级批量创建学生用户
        
        参数:
            class_name (str): 班级名称
        
        返回:
            tuple: (成功创建数量, 总数量)
        """
        success_count = 0
        total_count = 0
        
        try:
            self.db.connect()
            
            # 查询指定班级的所有学生
            self.db.cursor.execute(
                "SELECT student_id, name FROM student WHERE class_name = ?",
                (class_name,)
            )
            students = self.db.cursor.fetchall()
            
            if not students:
                print(f"错误：未找到班级 {class_name} 的学生信息")
                self.db.close()
                return 0, 0
            
            total_count = len(students)
            
            for student in students:
                student_id, name = student
                username = student_id  # 学号作为用户名
                password = student_id  # 学号作为初始密码
                role = 'student'  # 角色为学生
                
                # 检查用户名是否已存在
                self.db.cursor.execute(
                    "SELECT id FROM user WHERE username = ?",
                    (username,)
                )
                if self.db.cursor.fetchone():
                    print(f"错误：用户名 {username} 已存在，跳过")
                    continue
                
                # 对密码进行哈希处理
                hashed_password = hashlib.sha256(password.encode()).hexdigest()
                
                # 插入新用户
                try:
                    self.db.cursor.execute(
                        "INSERT INTO user (username, password, role, name) VALUES (?, ?, ?, ?)",
                        (username, hashed_password, role, name)
                    )
                    self.db.conn.commit()
                    success_count += 1
                    print(f"成功：学生用户 {username} ({name}) 创建成功")
                except Exception as e:
                    print(f"错误：创建学生用户 {username} 时发生错误 - {str(e)}")
                    self.db.conn.rollback()
            
            return success_count, total_count
        except Exception as e:
            print(f"错误：根据班级批量创建学生用户时发生错误 - {str(e)}")
            return success_count, total_count
        finally:
            self.db.close()

# 如果直接运行此文件，提供命令行界面
if __name__ == "__main__":
    creator = UserCreator()
    
    print("===== 用户创建 =====")
    username = input("请输入用户名: ")
    password = input("请输入密码: ")
    
    print("\n角色选项:")
    print("1. admin - 管理员")
    print("2. teacher - 老师")
    print("3. student - 学生")
    role_choice = input("请选择角色 (1-3): ")
    
    role = None
    if role_choice == '1':
        role = 'admin'
    elif role_choice == '2':
        role = 'teacher'
    elif role_choice == '3':
        role = 'student'
    else:
        print("错误：无效的角色选择")
        sys.exit(1)
    
    name = input("请输入姓名 (可选): ")
    contact = input("请输入联系方式 (可选): ")
    
    creator.create_user(username, password, role, name or None, contact or None)